// pages/order-detail/order-detail.js
var api = require('../../api.js');
var date =  require('../../utils/date.js');
var util = require('../../utils/util')
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
      bottom: app.BOTTOM_DISTANCE,//iponeX底部需要抬高的距离
      imgServer :  api.default.img_server,
      orderStatus:null,//订单状态值
      order: null,
      getGoodsTotalPrice: function () {
          return this.data.order.total_price;
      },
      returnAddress:{},//用户退回商品的地址
      addressPop:false,//弹窗
      moneyIcon:api.MONEYICON,
      moneyIconOther:api.MONEYICONOTHER,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
       if(options.id){
           this.setData({
               id:options.id,
           })
           this.getOrderDetail();
       }
    },
    checkReturnAddress(e){
      let address = e.currentTarget.dataset.address;
      console.log(address);
      this.setData({
        returnAddress:address,
        addressPop:true
      })
      
      console.log("ADADADADADADA")
    },
    onClose(){
      this.setData({
        addressPop:false,
      })
    },
    getOrderDetail(){
        var page = this;
        app.request({
            url: api.order.detail,
            data: {
                id: page.data.id,
            },
            success: function (res) {
                if (res.code == 200) {
                    let productNum =0;
                    for(const item of res.data.orderItemList){
                        productNum += item.productQuantity;
                    }
                    res.data.num = productNum;
                    //已申请售后的产品列表
                    let tempReturnApply = res.data.omsOrderReturnApply;
                    let temporderItemList= res.data.orderItemList;
                    if(tempReturnApply && tempReturnApply.length>0){
                        tempReturnApply.map((item)=>{
                            temporderItemList.map((item1)=>{
                                if(item.orderItemId == item1.id){
                                    item1.isreturnApply = true;
                                    //售后申请通过，需要用户将商品寄回到指定地址
                                    if(item.companyAddressId && Object.keys(item.companyAddress).length>0 && res.data.status==7){
                                      item1.returnAddress = item.companyAddress
                                    }
                                    item1.returnApply = item;
                                }
                            })  
                        })
                    }
                    //let createTime1 = res.data.createTime.split('.')[0].replace(/T/g,' ');
                //     let payTime ='';
                //   if (res.data.status > 0 && res.data.paymentTime){
                //     //let str2 = res.data.paymentTime.split('.')[0].replace(/T/g, ' ').replace(/-/g, '/');
                //     //payTime = date.datetimeFormat(new Date(str2).getTime());

                //     let str2 = new Date(res.data.paymentTime).toLocaleString();
                //     //Date.parse(res.data.paymentTime.replace(/-/g, '/'));
                //     //payTime = util.formatTime(str2);
                //     payTime = str2;
                //   }
                //   res.data.paymentTime = payTime;
                //   let str = res.data.createTime.split('.')[0].replace(/T/g, ' ').replace(/-/g, '/');
                //   let createTime2 = date.datetimeFormat(new Date(str).getTime());
                //   res.data.createTime = createTime2;
                  page.setData({
                      order: res.data,
                      orderStatus : res.data.status
                  });
                }
            },
            complete: function () {
                wx.hideLoading();
            }
        });
    },
    copyText: function (e) {
        var page = this;
        var text = e.currentTarget.dataset.text;
        wx.setClipboardData({
            data: text,
            success: function () {
                wx.showToast({
                    title: "已复制"
                });
            }
        });
    },
    checkExpressDetail(){
        wx.navigateTo({
          url: '/pages/express-detail/express-detail?expressid='+this.data.order.deliverySn,
        })
    },
    //确认收货
    onConfirmOrder(){
        let self = this;
        let orderId = self.data.order.id;
        wx.showModal({
            title: '提示',
            content: '是否确认收货？',
            success (res) {
              if (res.confirm) {
                app.request({
                    url:api.order.confirmProduct+orderId,
                    success(res){
                        if(res.code ==200){
                            wx.showToast({
                              title: '确认收货成功！',
                              icon:'none'
                            });
                            self.getOrderDetail();
                        }
                    }
                })
              } 
            }
          })
    },
    //取消订单
    cancleOrderFun(){
        let self = this;
        let orderId = self.data.order.id;
        wx.showModal({
            title: '提示',
            content: '是否确认取消订单？',
            success (res) {
              if (res.confirm) {
                app.request({
                    url:api.order.cancleOrder+orderId,
                    success(res){
                        if(res.code ==200){
                            wx.showToast({
                              title: '已关闭订单',
                              icon:'none'
                            })
                            self.getOrderDetail();
                        }
                    }
                })
              }
            }
          }) 
    },
    //立即支付
    payOrder(){
        //功能待完善
        let self = this;
        let orderSn = self.data.order.orderSn;
      let productType = self.data.order.productType;
        app.request({
          url: api.order.payOrderDetail,
          method:"post",
          data:{
            orderSn: orderSn,
            payType:2,
            productType: productType
          },
          success(res){
            if(res.code ==200){
              let sdk_params ='';
              if (res.data.sdk_params){
                 sdk_params =JSON.parse(res.data.sdk_params);
              }else{
                wx.showToast({
                  title: '支付异常',
                  icon:"none"
                })
                return
              }
              console.log(sdk_params);
                // //发起支付
                wx.requestPayment({
                  timeStamp: sdk_params.timeStamp,
                  nonceStr: sdk_params.nonceStr,
                  package: sdk_params.package,
                  signType: sdk_params.signType,
                  paySign: sdk_params.paySign,
                  success: function (e) {
                    wx.showModal({
                        title: '提示',
                        content: '支付成功~',
                        cancelText:'返回首页',
                        confirmText:'查看订单',
                            success (res) {
                            if (res.confirm) {
                                wx.redirectTo({
                                    url: "/pages/order/order?id="+self.data.id,//订单详情
                                });
                            } else if (res.cancel) {
                                wx.switchTab({
                                    url:'/pages/index/index',//返回首页
                                })
                            }
                            }
                        })
                  },
                  fail: function (e) {
                  },
                  complete: function (e) {
                      if (e.errMsg == "requestPayment:fail" || e.errMsg == "requestPayment:fail cancel") {//支付失败转到待支付订单列表
                        //   wx.showModal({
                        //       title: "提示",
                        //       content: "订单尚未支付",
                        //       showCancel: false,
                        //       confirmText: "确认",
                        //       success: function (res) {
                        //           if (res.confirm) {
                        //               wx.redirectTo({
                        //                   url: "/pages/order/order?status=0",//待支付列表
                        //               });
                        //           }
                        //       }
                        //   });
                        wx.showToast({
                          title: '订单尚未支付',
                          icon:'none'
                        })
                          return;
                      }
                      if (e.errMsg == "requestPayment:ok") {
                          return;
                      }
                      wx.redirectTo({
                          url: "/pages/order/order?status=1",
                      });
                    },
                  });
              }else{
                wx.showToast({
                  title: res.message||'订单支付出现异常',
                  icon:"none"
                })
              }
            }
        })
    }
});